# -!- coding: utf-8 -!-
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
#作者：cacho_37967865
#博客：https://blog.csdn.net/sinat_37967865
#文件：deal_image.py
#日期：2019-10-19
#备注：对图片换底色
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

from PIL import Image,ImageEnhance
from itertools import product
from pycacho.cachobase.file_deal import an_save_txt
from pycacho.cachobase.logger import Logger
logger = Logger("deal_image").get_log()
import random

dots =[(2,2,2),(2,2,2),(2,2,2),(2,2,2)]
transparent_pix = (239,239,239)  # 透明的
random_dots = (random.randint(30,60),random.randint(30,60),random.randint(30,60))


# 对图片进行处理
def deal_image(infile,outfile):
    im = Image.open(infile)
    enhancer = ImageEnhance.Contrast(im)
    im = enhancer.enhance(2)
    im = im.convert('1')
    data = im.getdata()
    w, h = im.size
    black_point = 0
    for x in range(1, w - 1):
        for y in range(1, h - 1):
            mid_pixel = data[w * y + x]  # 中央像素点像素值
            if mid_pixel == 0:  # 找出上下左右四个方向像素点像素值
                top_pixel = data[w * (y - 1) + x]
                left_pixel = data[w * y + (x - 1)]
                down_pixel = data[w * (y + 1) + x]
                right_pixel = data[w * y + (x + 1)]

                # 判断上下左右的黑色像素点总个数
                if top_pixel == 0:
                    black_point += 1
                if left_pixel == 0:
                    black_point += 1
                if down_pixel == 0:
                    black_point += 1
                if right_pixel == 0:
                    black_point += 1
                if black_point >= 3:
                    im.putpixel((x, y), 0)
                # print black_point
                black_point = 0
    im.show()
    im.save(outfile)


def get_pix(infile):
    img = Image.open(infile)
    w, h = img.size
    #print(w,h)
    #an_save_txt('./images/id.txt',str(w)+'--'+str(h))
    for i in range(w):
        for j in range(h):
            L = img.getpixel((i, j))
            if L[0]>80 and L[1]>80 and L[2]>80 and i>120 and i<191 and j>0 and j<50:
                print(L)
                img.putpixel((i, j), (255, 0, 0,255))
            #an_save_txt('./images/id.txt', str(i+1) + '--' + str(j+1) + '--' + str(L))
    img.save("./images/id_1.png", "PNG")
    img.show()

# 对背景色处理: 0=替换某个颜色
def transparent(infile,type):
    img = Image.open(infile)
    new_png = img.convert('RGBA')
    L, H = new_png.size         #图片尺寸
    color_0 = new_png.getpixel((0, 0))   # 返回图片某个坐标点颜色。
    logger.info('返回图片某个坐标点颜色%s', color_0)
    for h in range(H):
        for l in range(L):
            dot = (l, h)
            if type == 'change':
                color_1 = new_png.getpixel(dot)
                #if ((l<251 or l>936) or (248<l<940 and (h>1061 or h<144))) and \
                if 240 < color_1[0] < 256 and 240 < color_1[1] < 256 and 240 < color_1[2] < 256:
                    new_png.putpixel(dot,transparent_pix)  # (255,255,255,255)
                else:
                    print(h, l, color_1)
                    new_png.putpixel(dot, color_1)
            else:
                pass
    new_png.save("F:\\4-c.png", "png")
    #new_png.show()

# 更改颜色: 0=替换某个固定颜色
def change_color(infile,type):
    changed_pix = (255,108,55)
    img = Image.open(infile).convert('RGBA')
    L, H = img.size         #图片尺寸
    for h in range(H):
        for l in range(L):
            dot = (l, h)
            if type == '0':
                color_1 = img.getpixel(dot)
                if color_1[0] ==89 and color_1[1]==185 and color_1[2]==111:
                    img.putpixel(dot,changed_pix)  # (255,255,255,255)
                else:
                    print(h, l, color_1)
                    img.putpixel(dot, color_1)
            elif type == '1':
                color_1 = img.getpixel(dot)
                if 80<color_1[0] < 100 and 170<color_1[1]< 200 and 100<color_1[2] < 120:
                    img.putpixel(dot, changed_pix)  # (255,255,255,255)
                else:
                    print(h, l, color_1)
                    img.putpixel(dot, color_1)
            else:
                pass
    img.save("F:\\alibaba\公司信息\\bb1-2.png", "png")


# 创建背景色，补全图片为正方形
def create_background(infile,type,length):
    img = Image.open(infile)
    k = img.width  # k-宽度，
    g =img.height       # g-高度
    if g<k and type!='Q':  # 宽度>高度，
        new_image = Image.new("RGB", (k, k), "#FFFFFF")
        add_u = int((k - g) / 2)  # 上面分割需要补全长度的一半
    elif g>k and type!='Q':
        new_image = Image.new("RGB", (g, g), "#FFFFFF")
        add_u = int((g - k) / 2)  # 左边分割需要补全长度的一半
    else:
        new_image = Image.new("RGB", (k+length[0]+length[2], g+length[1]+length[3]), "#FFFFFF")  # 白色
        add_u = int((k+length[0]+length[2] - g) / 2)  # 上面分割需要补全长度的一半
    L, H = new_image.size  # 必须为L,H
    print(L, H,add_u)
    if type=='H2':  # 补全上下，为正方形
        for h in range(H):
            for l in range(L):
                dot = (l, h)
                if h<add_u:
                    color_0 = img.getpixel((l, 1))   # 上面补全图片上边界
                elif h>g-1+add_u:     # 图片高度-1 再加上上面补全长度
                    color_0 = img.getpixel((l, g-1))   # 下面补全图片下边界
                else:
                    color_0 = img.getpixel((l, h-add_u))  # 中间部分复制原图片
                new_image.putpixel(dot, color_0)
    elif type=='L2':  # 补全左右，为正方形
        print('开始补全图片左右两边.....')
        for h in range(H):
            for l in range(L):
                dot = (l, h)
                if l<add_u:
                    color_0 = img.getpixel((1, h))   # 补全图片左边界
                    #color_0 = (255,255,255)
                elif l>k-1+add_u:     # 图片宽度-1 再加上上面补全长度
                    color_0 = img.getpixel((k-1, h))   # 补全图片右边界
                    #color_0 = (255,255,255)
                else:
                    color_0 = img.getpixel((l-add_u, h))  # 中间部分复制原图片
                new_image.putpixel(dot, color_0)
    else:                     # 补全四周
        for h in range(H):
            for l in range(L):
                dot = (l, h)
                if length[1]<h < g-1+length[1] and length[0]<l<k-1+length[0]:
                    color_0 = img.getpixel((l-length[0], h-length[1]))  # 中间部分复制
                else:
                    color_0 = (239,239,239)      # 固定色块 (255,255,255)，(0,0,0)
                    #color_0 = img.getpixel((l, 0))   # 仅仅上面添加
                    #color_0 = img.getpixel((l, g-1))   # 仅仅下面添加
                    #color_0 = img.getpixel((length[1], h))  # 仅仅左边添加
                    #color_0 = img.getpixel((k-1, h))  # 仅仅右边添加
                new_image.putpixel(dot, color_0)
    new_image.save("F:\\alibaba\公司信息\\bb1-2.jpg", quality=100)


# 合并图片 file:上面图片，background：背景图片
def merge_image(background,file):
    img = Image.open(background).convert('RGBA')
    out = Image.open(file).convert('RGBA')
    img.paste(out,(500,500))
    img.save('./file/out.png','PNG')


# 去除图片水印（文字）:infile-需要处理的图片，width-需要处理的宽度，length-需要处理的高度
def remove_log(infile,width,length):
    img = Image.open(infile)
    L, H = img.size
    for h in range(H):
        for l in range(L):
            dot = (l, h)
            #or l<6 :     # (4437,5120)
                #img.putpixel(dot, (245,235,200))  # 深蓝(49,147,132)  黄(245,235,200),蓝(64,169,152)
            if h>8200:
                #pass
                img.putpixel(dot, (255,255,255))
    img.save("F:\\b0-4.jpg",quality=100)

def crop_image(file):
    img = Image.open(file)
    box = (0, 0, 1920, 8304)    # 四元组的坐标依次是（左，上，右，下）
    img.crop(box).save("F:\\b0-4.jpg",quality=100)  # 从一幅图像中裁剪指定区域

# 创建一个单纯的背景色
def background_image():
    new_image = Image.new("RGB", (1920, 500), (239,239,239))
    new_image.save("F:\\alibaba\公司信息\\b0-4.jpg", quality=100)

# 缩小放大
def resize_image(file,out_file):
    im = Image.open(file)
    image = im.resize((700, 700))
    image.save(out_file,quality=100)

if __name__ == '__main__':
    #get_pix('./images/id_1.png')
    #transparent('F:\\图片4-c.png','change')
    #transparent('./file/a.jpg','')
    #merge_image('./file/a-copy.png', './file/c-copy.png')
    #create_background("F:\\alibaba\公司信息\\bb1-0.jpg",'Q',[50,0,50,0])  # l-左边，r-右边，u-上面，d-下面，L2-左右，H2-上下，Q-手工添加大小([0,40,50,50]=左，上，右，下)
    #remove_log('F:\\alibaba\公司信息\\b.jpg',0,1195)
    #crop_image('F:\\alibaba\公司信息\\b.jpg')
    #change_color('F:\\alibaba\公司信息\\bb1-0.jpg','1')
    #background_image()
    resize_image('F:\\banner\\b_phone-2.png', 'F:\\banner\\b_phone-2-b.png')